<template>
  <div class="history">
    <a-card title="部署历史记录">
      <template #extra>
        <a-space>
          <a-button @click="loadHistory" :loading="loading">
            <template #icon>
              <ReloadOutlined />
            </template>
            刷新
          </a-button>
          <a-button 
            @click="showClearConfirm" 
            danger
            :disabled="!historyList.length"
          >
            <template #icon>
              <DeleteOutlined />
            </template>
            清空历史
          </a-button>
        </a-space>
      </template>

      <!-- 筛选和搜索 -->
      <div class="filter-section">
        <a-row :gutter="16" style="margin-bottom: 16px;">
          <a-col :span="6">
            <a-select
              v-model:value="filters.status"
              placeholder="筛选状态"
              allow-clear
              style="width: 100%"
              @change="handleFilterChange"
            >
              <a-select-option value="success">成功</a-select-option>
              <a-select-option value="failed">失败</a-select-option>
              <a-select-option value="running">运行中</a-select-option>
            </a-select>
          </a-col>
          <a-col :span="6">
            <a-range-picker
              v-model:value="filters.dateRange"
              style="width: 100%"
              @change="handleFilterChange"
              :placeholder="['开始日期', '结束日期']"
            />
          </a-col>
          <a-col :span="6">
            <a-input
              v-model:value="filters.branch"
              placeholder="筛选分支"
              allow-clear
              @change="handleFilterChange"
            >
              <template #prefix>
                <BranchesOutlined />
              </template>
            </a-input>
          </a-col>
          <a-col :span="6">
            <a-input
              v-model:value="filters.message"
              placeholder="搜索提交信息"
              allow-clear
              @change="handleFilterChange"
            >
              <template #prefix>
                <SearchOutlined />
              </template>
            </a-input>
          </a-col>
        </a-row>
      </div>

      <!-- 批量操作 -->
      <div v-if="selectedRowKeys.length > 0" class="batch-actions">
        <a-alert
          :message="`已选择 ${selectedRowKeys.length} 条记录`"
          type="info"
          show-icon
          style="margin-bottom: 16px;"
        >
          <template #action>
            <a-button 
              size="small" 
              danger 
              @click="batchDelete"
              :loading="batchDeleteLoading"
            >
              批量删除
            </a-button>
          </template>
        </a-alert>
      </div>

      <!-- 历史记录表格 -->
      <a-table
        :columns="columns"
        :data-source="historyList"
        :loading="loading"
        :pagination="pagination"
        :row-selection="rowSelection"
        row-key="id"
        @change="handleTableChange"
        size="middle"
      >
        <!-- 状态列 -->
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <a-tag :color="getStatusColor(record.status)">
              <template #icon>
                <component :is="getStatusIcon(record.status)" />
              </template>
              {{ getStatusText(record.status) }}
            </a-tag>
          </template>

          <!-- 分支列 -->
          <template v-else-if="column.key === 'branch'">
            <a-tag color="blue">
              <BranchesOutlined />
              {{ record.branch || 'main' }}
            </a-tag>
          </template>

          <!-- 提交信息列 -->
          <template v-else-if="column.key === 'message'">
            <div class="commit-message">
              <a-tooltip :title="record.message">
                <span>{{ truncateText(record.message, 50) }}</span>
              </a-tooltip>
              <div class="commit-info">
                <a-typography-text type="secondary" style="font-size: 12px;">
                  {{ record.commitHash ? record.commitHash.substring(0, 8) : 'N/A' }}
                  <span v-if="record.author"> · {{ record.author }}</span>
                </a-typography-text>
              </div>
            </div>
          </template>

          <!-- 时间列 -->
          <template v-else-if="column.key === 'createdAt'">
            <div>
              <div>{{ formatTime(record.createdAt) }}</div>
              <a-typography-text type="secondary" style="font-size: 12px;">
                耗时: {{ getDuration(record.createdAt, record.updatedAt) }}
              </a-typography-text>
            </div>
          </template>

          <!-- 操作列 -->
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button 
                type="link" 
                size="small" 
                @click="viewLogs(record)"
                :loading="record.id === currentRecord?.id && loading"
              >
                查看日志
              </a-button>
              <a-button 
                type="link" 
                size="small" 
                @click="viewDetails(record)"
              >
                详情
              </a-button>
              <a-popconfirm
                title="确定要删除这条记录吗？"
                @confirm="deleteRecord(record.id)"
                ok-text="确定"
                cancel-text="取消"
              >
                <a-button 
                  type="link" 
                  size="small" 
                  danger
                  :disabled="record.status === 'running'"
                >
                  删除
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 日志查看模态框 -->
    <a-modal
      v-model:open="logModalVisible"
      title="部署日志"
      width="80%"
      :footer="null"
      :destroy-on-close="true"
    >
      <div class="log-viewer">
        <div class="log-header">
          <a-space>
            <a-tag :color="getStatusColor(currentRecord?.status)">
              {{ getStatusText(currentRecord?.status) }}
            </a-tag>
            <span>{{ currentRecord?.message }}</span>
            <a-typography-text type="secondary">
              {{ formatTime(currentRecord?.startTime) }}
            </a-typography-text>
          </a-space>
        </div>
        
        <div class="log-content">
          <a-spin :spinning="logLoading">
            <div v-if="logs.length === 0 && !logLoading" class="no-logs">
              <a-empty description="暂无日志数据" />
            </div>
            <div v-else class="log-lines">
              <div
                v-for="(log, index) in logs"
                :key="index"
                :class="['log-line', `log-${log.level || 'info'}`]"
              >
                <span class="log-time">{{ formatLogTime(log.timestamp) }}</span>
                <span class="log-level">{{ (log.level || 'INFO').toUpperCase() }}</span>
                <span class="log-message">{{ log.message }}</span>
              </div>
            </div>
          </a-spin>
        </div>
      </div>
    </a-modal>

    <!-- 详情查看模态框 -->
    <a-modal
      v-model:open="detailModalVisible"
      title="部署详情"
      width="600px"
      :footer="null"
    >
      <div v-if="currentRecord" class="detail-content">
        <a-descriptions :column="1" bordered>
          <a-descriptions-item label="部署ID">
            {{ currentRecord.id }}
          </a-descriptions-item>
          <a-descriptions-item label="状态">
            <a-tag :color="getStatusColor(currentRecord.status)">
              <template #icon>
                <component :is="getStatusIcon(currentRecord.status)" />
              </template>
              {{ getStatusText(currentRecord.status) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="分支">
            <a-tag color="blue">
              <BranchesOutlined />
              {{ currentRecord.branch || 'main' }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="提交信息">
            {{ currentRecord.message }}
          </a-descriptions-item>
          <a-descriptions-item label="提交哈希">
            <a-typography-text code>
              {{ currentRecord.commitHash || 'N/A' }}
            </a-typography-text>
          </a-descriptions-item>
          <a-descriptions-item label="作者">
            {{ currentRecord.author || 'N/A' }}
          </a-descriptions-item>
          <a-descriptions-item label="开始时间">
              {{ formatTime(currentRecord?.createdAt) }}
            </a-descriptions-item>
          <a-descriptions-item label="结束时间">
              {{ currentRecord.updatedAt ? formatTime(currentRecord.updatedAt) : '未完成' }}
            </a-descriptions-item>
            <a-descriptions-item label="耗时">
              {{ getDuration(currentRecord.createdAt, currentRecord.updatedAt) }}
            </a-descriptions-item>
          <a-descriptions-item v-if="currentRecord.error" label="错误信息">
            <a-typography-text type="danger">
              {{ currentRecord.error }}
            </a-typography-text>
          </a-descriptions-item>
        </a-descriptions>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { message, Modal } from 'ant-design-vue'
import dayjs from 'dayjs'
import api from '../services/api'
import {
  ReloadOutlined,
  DeleteOutlined,
  SearchOutlined,
  BranchesOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  LoadingOutlined,
  ClockCircleOutlined
} from '@ant-design/icons-vue'

// 响应式数据
const loading = ref(false)
const logLoading = ref(false)
const batchDeleteLoading = ref(false)
const historyList = ref([])
const logs = ref([])
const currentRecord = ref(null)
const selectedRowKeys = ref([])

// 模态框状态
const logModalVisible = ref(false)
const detailModalVisible = ref(false)

// 筛选条件
const filters = reactive({
  status: undefined,
  dateRange: undefined,
  branch: '',
  message: ''
})

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
})

// 表格列配置
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 80,
    sorter: true
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100
  },
  {
    title: '分支',
    dataIndex: 'branch',
    key: 'branch',
    width: 120
  },
  {
    title: '提交信息',
    dataIndex: 'message',
    key: 'message',
    ellipsis: true
  },
  {
    title: '时间',
    dataIndex: 'createdAt',
    key: 'createdAt',
    width: 180,
    sorter: true
  },
  {
    title: '操作',
    key: 'action',
    width: 200
  }
]

// 行选择配置
const rowSelection = computed(() => ({
  selectedRowKeys: selectedRowKeys.value,
  onChange: (keys) => {
    selectedRowKeys.value = keys
  },
  getCheckboxProps: (record) => ({
    disabled: record.status === 'running'
  })
}))

// 方法
const loadHistory = async () => {
  try {
    loading.value = true
    
    const params = {
      offset: (pagination.current - 1) * pagination.pageSize,
      limit: pagination.pageSize,
      ...getFilterParams()
    }
    
    const response = await api.getHistory(params)
    if (response.success) {
      historyList.value = response.data || []
      pagination.total = response.pagination?.total || 0
    } else {
      message.error(response.message || '加载历史记录失败')
    }
  } catch (error) {
    message.error('加载历史记录失败')
    console.error('加载历史记录失败:', error)
  } finally {
    loading.value = false
  }
}

const getFilterParams = () => {
  const params = {}
  
  if (filters.status) {
    params.status = filters.status
  }
  
  if (filters.dateRange && filters.dateRange.length === 2) {
    params.startTime = filters.dateRange[0].format('YYYY-MM-DD HH:mm:ss')
    params.endTime = filters.dateRange[1].format('YYYY-MM-DD HH:mm:ss')
  }
  
  if (filters.branch) {
    params.branch = filters.branch
  }
  
  if (filters.message) {
    params.message = filters.message
  }
  
  return params
}

const handleFilterChange = () => {
  pagination.current = 1
  loadHistory()
}

const handleTableChange = (pag, filters, sorter) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  
  // 处理排序
  if (sorter && sorter.field) {
    // 这里可以添加排序逻辑
  }
  
  loadHistory()
}

const viewLogs = async (record) => {
  try {
    currentRecord.value = record
    logModalVisible.value = true
    logLoading.value = true
    logs.value = []
    
    const response = await api.getDeployLogs(record.id)
    if (response.success) {
      // 处理日志数据结构
      if (response.data && response.data.logs) {
        logs.value = response.data.logs || []
      } else {
        // 如果直接从记录中获取日志
        logs.value = record.logs || []
      }
    } else {
      message.error('获取日志失败')
    }
  } catch (error) {
    message.error('获取日志失败')
    console.error('获取日志失败:', error)
  } finally {
    logLoading.value = false
  }
}

const viewDetails = (record) => {
  currentRecord.value = record
  detailModalVisible.value = true
}

const deleteRecord = async (id) => {
  try {
    const response = await api.deleteHistoryRecord(id)
    if (response.success) {
      message.success('删除成功')
      await loadHistory()
    } else {
      message.error(response.message || '删除失败')
    }
  } catch (error) {
    message.error('删除失败')
    console.error('删除失败:', error)
  }
}

const batchDelete = async () => {
  try {
    batchDeleteLoading.value = true
    const response = await api.batchDeleteHistory(selectedRowKeys.value)
    if (response.success) {
      message.success(`成功删除 ${selectedRowKeys.value.length} 条记录`)
      selectedRowKeys.value = []
      await loadHistory()
    } else {
      message.error(response.message || '批量删除失败')
    }
  } catch (error) {
    message.error('批量删除失败')
    console.error('批量删除失败:', error)
  } finally {
    batchDeleteLoading.value = false
  }
}

const showClearConfirm = () => {
  Modal.confirm({
    title: '确认清空',
    content: '确定要清空所有历史记录吗？此操作不可恢复。',
    okText: '确定',
    cancelText: '取消',
    okType: 'danger',
    onOk: clearAllHistory
  })
}

const clearAllHistory = async () => {
  try {
    const response = await api.clearHistory()
    if (response.success) {
      message.success('历史记录已清空')
      historyList.value = []
      pagination.total = 0
      selectedRowKeys.value = []
    } else {
      message.error(response.message || '清空失败')
    }
  } catch (error) {
    message.error('清空失败')
    console.error('清空失败:', error)
  }
}

// 工具方法
const getStatusColor = (status) => {
  const colors = {
    success: 'success',
    failed: 'error',
    running: 'processing'
  }
  return colors[status] || 'default'
}

const getStatusIcon = (status) => {
  const icons = {
    success: CheckCircleOutlined,
    failed: CloseCircleOutlined,
    running: LoadingOutlined
  }
  return icons[status] || ClockCircleOutlined
}

const getStatusText = (status) => {
  const texts = {
    success: '成功',
    failed: '失败',
    running: '运行中'
  }
  return texts[status] || '未知'
}

const formatTime = (time) => {
  if (!time) return 'N/A'
  return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}

const formatLogTime = (time) => {
  if (!time) return ''
  return dayjs(time).format('HH:mm:ss.SSS')
}

const getDuration = (startTime, endTime) => {
  if (!startTime) return 'N/A'
  if (!endTime) return '进行中'
  
  const start = dayjs(startTime)
  const end = dayjs(endTime)
  const duration = end.diff(start, 'second')
  
  if (duration < 60) {
    return `${duration}秒`
  } else if (duration < 3600) {
    const minutes = Math.floor(duration / 60)
    const seconds = duration % 60
    return `${minutes}分${seconds}秒`
  } else {
    const hours = Math.floor(duration / 3600)
    const minutes = Math.floor((duration % 3600) / 60)
    return `${hours}小时${minutes}分钟`
  }
}

const truncateText = (text, maxLength) => {
  if (!text) return 'N/A'
  if (text.length <= maxLength) return text
  return text.substring(0, maxLength) + '...'
}

// 生命周期
onMounted(() => {
  loadHistory()
})
</script>

<style scoped>
.history {
  padding: 24px;
}

.filter-section {
  background: #fafafa;
  padding: 16px;
  border-radius: 6px;
  margin-bottom: 16px;
}

.batch-actions {
  margin-bottom: 16px;
}

.commit-message {
  line-height: 1.4;
}

.commit-info {
  margin-top: 4px;
}

.log-viewer {
  height: 60vh;
  display: flex;
  flex-direction: column;
}

.log-header {
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 12px;
}

.log-content {
  flex: 1;
  overflow: hidden;
}

.log-lines {
  height: 100%;
  overflow-y: auto;
  background: #1e1e1e;
  color: #d4d4d4;
  padding: 12px;
  border-radius: 4px;
  font-family: 'Courier New', monospace;
  font-size: 13px;
  line-height: 1.4;
}

.log-line {
  margin-bottom: 2px;
  word-break: break-all;
}

.log-time {
  color: #569cd6;
  margin-right: 8px;
}

.log-level {
  display: inline-block;
  width: 50px;
  margin-right: 8px;
  font-weight: bold;
}

.log-message {
  color: #d4d4d4;
}

.log-info .log-level {
  color: #4ec9b0;
}

.log-warn .log-level {
  color: #dcdcaa;
}

.log-error .log-level {
  color: #f44747;
}

.log-debug .log-level {
  color: #9cdcfe;
}

.no-logs {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 200px;
}

.detail-content {
  max-height: 60vh;
  overflow-y: auto;
}
</style>